package com.ljfiction.book.activitys;

import android.content.Intent;
import android.graphics.drawable.BitmapDrawable;
import android.icu.text.DecimalFormat;
import android.os.Build;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.google.gson.Gson;
import com.ljfiction.book.Baner.MyBookEasyBean;
import com.ljfiction.book.Baner.MyshouruAllBean;
import com.ljfiction.book.Dialog.NoBackgLodDialog;
import com.ljfiction.book.MyView.BorderTextView;
import com.ljfiction.book.MyView.DividerItemDecoration;
import com.ljfiction.book.MyView.SuperButton;
import com.ljfiction.book.R;
import com.ljfiction.book.calendartest.SharePreferences;
import com.ljfiction.book.http.HttpManager;
import com.ljfiction.book.tools.AppUtils;
import com.ljfiction.book.tools.ScreenUtils;
import com.ljfiction.book.tools.SettingManager;
import com.lzy.okhttputils.OkHttpUtils;
import com.lzy.okhttputils.callback.StringCallback;
import com.lzy.okhttputils.request.BaseRequest;
import com.zhy.autolayout.utils.AutoUtils;

import org.json.JSONObject;

import java.io.Serializable;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Call;
import okhttp3.Response;

public class MyincomeActivity extends BaseActivity {

    @BindView(R.id.back_myincome)
    ImageView backMyincome;
    @BindView(R.id.myincomemoney)
    TextView myincomemoney;

    @BindView(R.id.subscription_muincome)
    TextView subscriptionMuincome;
    @BindView(R.id.recommend_myincome)
    TextView recommendMyincome;
    @BindView(R.id.giveareward_myincome)
    TextView givearewardMyincome;
    @BindView(R.id.recommended_myincome)
    TextView recommendedMyincome;
    @BindView(R.id.sectionfordetails)
    SuperButton sectionfordetails;

    @BindView(R.id.myincome_spinner)
    TextView myincomeSpinner;
    @BindView(R.id.booklist)
    RelativeLayout booklist;
    @BindView(R.id.select_time)
    TextView selectTime;
    @BindView(R.id.dayselect)
    LinearLayout dayselect;
    @BindView(R.id.chaptermuch)
    RelativeLayout chaptermuch;

    private DecimalFormat df;
    private MyshouruAllBean myshouruAllBean;
    private List<MyBookEasyBean.DataBean.AlldataBean> booknamelsit = new ArrayList<>();
    private MyBookEasyBean myBookEasyBean;
    private Calendar calendar;
    private int start_year;
    private int start_month;
    private int start_day;
    private int end_year;
    private int end_month;
    private int end_day;
    private Intent intent;
    private MyBookEasyBean.DataBean.AlldataBean allBook;
    private int posistion = 0;//选中的书
    private NoBackgLodDialog noBackgLodDialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_myincome);
        ButterKnife.bind(this);
AppUtils.init(this);

        calendar = Calendar.getInstance();
        allBook = new MyBookEasyBean.DataBean.AlldataBean();
        allBook.setBookName("全部小说");
        inttime();
        booknamelsit.add(allBook);
        intMoneyData();

    }

    private PopupWindow popupWindow;
    private RecyclerView recycleview;
    private BaseQuickAdapter mAdapter;

    private void showPopuWindow(View view) {
        View contentView = LayoutInflater.from(this).inflate(R.layout.selectbook_recycle, null);
        popupWindow = new PopupWindow(contentView);
        recycleview = contentView.findViewById(R.id.selectBook_recycleview);
        recycleview.setLayoutManager(new LinearLayoutManager(this));
        recycleview.addItemDecoration(new DividerItemDecoration(this, DividerItemDecoration.VERTICAL_LIST));
        recycleview.setAdapter(mAdapter = new BaseQuickAdapter<MyBookEasyBean.DataBean.AlldataBean, BaseViewHolder>(R.layout.selectbook_item, booknamelsit) {
            @Override
            protected void convert(BaseViewHolder helper, MyBookEasyBean.DataBean.AlldataBean item) {
                AutoUtils.autoSize(helper.itemView);
                helper.setText(R.id.bookName_selectitem, item.getBookName());
            }
        });
        mAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                posistion = position;
                if (position == 0) {
                    if (booknamelsit.size() > 1) {
                        toAllBookManey();
                    }
                } else {
                    toOneBookManey(booknamelsit.get(position).getBookid());
                }
                myincomeSpinner.setText(booknamelsit.get(position).getBookName());
                if (popupWindow != null) {
                    popupWindow.dismiss();
                }
            }
        });
        //使其聚集
        popupWindow.setFocusable(true);
        // 设置允许在外点击消失
        popupWindow.setOutsideTouchable(true);
        //这个是为了点击“返回Back”也能使其消失，并且并不会影响背景
        popupWindow.setBackgroundDrawable(new BitmapDrawable());
        // 设置SelectPicPopupWindow弹出窗体的宽
        popupWindow.setWidth(ScreenUtils.getScreenWidth());
        popupWindow.setHeight(ScreenUtils.getScreenHeight() * 1 / 2);
        // 设置SelectPicPopupWindow弹出窗体动画效果
        // popupWindow.setAnimationStyle(R.style.AnimBottom);
        //popupWindow.setBackgroundDrawable(getResources().getDrawable(R.drawable.back_search_img));
        popupWindow.showAsDropDown(view);
    }

    private void toOneBookManey(int bookId) {
        OkHttpUtils.post(HttpManager.IP + "/allincomestatisticsByBookId")

                .params("startdate", start_year + "-" + isDan(start_month) + "-" + isDan(start_day) + " 00:00:00")
                .params("enddate", end_year + "-" + isDan(end_month) + "-" + isDan(end_day) + " 23:59:59")
                .params("bookid", String.valueOf(bookId))
                .execute(new StringCallback() {
                    @Override
                    public void onBefore(BaseRequest request) {
                        super.onBefore(request);
                        if (noBackgLodDialog==null){
                            noBackgLodDialog=new NoBackgLodDialog(MyincomeActivity.this,true);
                        }
                        noBackgLodDialog.show();
                    }

                    @Override
                    public void onSuccess(String s, Call call, Response response) {
                        if (noBackgLodDialog!=null){
                            noBackgLodDialog.dismis();
                        }
                        try {
                            JSONObject jsonObject = new JSONObject(s);
                            if (jsonObject.getInt("returnCode") == 200) {
                                Gson gson = new Gson();
                                myshouruAllBean = gson.fromJson(jsonObject.getString("data"), MyshouruAllBean.class);
                                toIntView();
                            }else if (jsonObject.getInt("returnCode") == 400){
                                Intent intent=new Intent(MyincomeActivity.this,LoginActivity.class);
                                startActivity(intent);
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                });
    }

    private void toAllBookManey() {
        OkHttpUtils.post(HttpManager.IP + "/allincomestatistics")

                .params("startdate", start_year + "-" + isDan(start_month) + "-" + isDan(start_day) + " 00:00:00")
                .params("enddate", end_year + "-" + isDan(end_month) + "-" + isDan(end_day) + " 23:59:59")
                .execute(new StringCallback() {
                    @Override
                    public void onBefore(BaseRequest request) {
                        super.onBefore(request);
                        if (noBackgLodDialog==null){
                            noBackgLodDialog=new NoBackgLodDialog(MyincomeActivity.this,true);
                        }
                        noBackgLodDialog.show();
                    }

                    @Override
                    public void onSuccess(String s, Call call, Response response) {
                        if (noBackgLodDialog!=null){
                            noBackgLodDialog.dismis();
                        }
                        try {
                            JSONObject jsonObject = new JSONObject(s);
                            if (jsonObject.getInt("returnCode") == 200) {
                                Gson gson = new Gson();
                                myshouruAllBean = gson.fromJson(jsonObject.getString("data"), MyshouruAllBean.class);
                                toIntView();
                            }else if (jsonObject.getInt("returnCode") == 400){
                                Intent intent=new Intent(MyincomeActivity.this,LoginActivity.class);
                                startActivity(intent);
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                });
    }

    private void intMoneyData() {

        OkHttpUtils.post(HttpManager.IP + "/allincomestatistics")

                .params("startdate", start_year + "-" + isDan(start_month) + "-" + isDan(start_day) + " 00:00:00")
                .params("enddate", end_year + "-" + isDan(end_month) + "-" + isDan(end_day) + " 23:59:59")
                .execute(new StringCallback() {
                    @Override
                    public void onBefore(BaseRequest request) {
                        super.onBefore(request);
                        if (noBackgLodDialog==null){
                            noBackgLodDialog=new NoBackgLodDialog(MyincomeActivity.this,true);
                        }
                        noBackgLodDialog.show();
                    }

                    @Override
                    public void onSuccess(String s, Call call, Response response) {
                        if (noBackgLodDialog!=null){
                            noBackgLodDialog.dismis();
                        }
                        try {
                            JSONObject jsonObject = new JSONObject(s);
                            if (jsonObject.getInt("returnCode") == 200) {
                                Gson gson = new Gson();
                                myshouruAllBean = gson.fromJson(jsonObject.getString("data"), MyshouruAllBean.class);
                                myBookEasyBean = gson.fromJson(s, MyBookEasyBean.class);
                                toIntView();
                                booknamelsit.addAll(myBookEasyBean.getData().getAlldata());
                                mAdapter.notifyDataSetChanged();
                            }else if (jsonObject.getInt("returnCode") == 400){
                                Intent intent=new Intent(MyincomeActivity.this,LoginActivity.class);
                                startActivity(intent);
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                });
    }

    private void toIntView() {
        myincomemoney.setText(isAddAllDouhao(myshouruAllBean.getDaShang() + myshouruAllBean.getSubTotalMoney() + myshouruAllBean.getRecomm()));
        subscriptionMuincome.setText(isAddDouhao(myshouruAllBean.getSubTotalMoney()));
        recommendMyincome.setText(isAddDouhao(myshouruAllBean.getRecomm()/10));
        givearewardMyincome.setText(isAddDouhao(myshouruAllBean.getDaShang()));
        recommendedMyincome.setText(isAddDouhao(myshouruAllBean.getSubTotalCount()));
    }



    private SharePreferences isPreferences;

    private void inttime() {
        isPreferences = new SharePreferences(this);
        start_year = calendar.get(Calendar.YEAR);
        start_month = calendar.get(Calendar.MONTH) + 1;
        start_day = calendar.get(Calendar.DAY_OF_MONTH);
        end_year = calendar.get(Calendar.YEAR);
        end_month = calendar.get(Calendar.MONTH) + 1;
        end_day = calendar.get(Calendar.DAY_OF_MONTH);
        selectTime.setText(start_year + "."+start_month + "." + start_day + "-" +end_year+"."+ end_month + "." + end_day);
        isPreferences.updateSp("start_year", start_year);
        isPreferences.updateSp("start_month", start_month);
        isPreferences.updateSp("start_day", start_day);
        isPreferences.updateSp("end_year", end_year);
        isPreferences.updateSp("end_month", end_month);
        isPreferences.updateSp("end_day", end_day);
    }


    @OnClick({R.id.back_myincome, R.id.monthly_myincome, R.id.sectionfordetails, R.id.booklist,R.id.dayselect,R.id.chaptermuch})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.back_myincome:
                goBack();
                break;
            case R.id.monthly_myincome:
                intent = new Intent(MyincomeActivity.this, MonthlyActivity.class);
                intent.putExtra("booknamelist", (Serializable) booknamelsit);
                startActivity(intent);
                break;
            case R.id.sectionfordetails:
                intent=new Intent(MyincomeActivity.this,ApplymoneyActivity.class);
                startActivity(intent);
                break;
            case R.id.dayselect:
                startActivityForResult(new Intent(this, MonthTimeActivity.class), 1);
                break;
            case R.id.booklist:
                if (booknamelsit.size() < 2) {
                    showToast("还没有书籍");
                } else {
                    if (popupWindow != null && !popupWindow.isShowing()) {
                        popupWindow.showAsDropDown(view);
                    } else {
                        showPopuWindow(view);
                    }
                }
                break;
            case R.id.chaptermuch:
                if (posistion == 0) {
                    showToast("请选择一本书");
                    return;
                } else {
                    intent = new Intent(MyincomeActivity.this, ChapterMoneyActivity.class);
                    intent.putExtra("bookId", booknamelsit.get(posistion).getBookid());
                    intent.putExtra("start_year", start_year);
                    intent.putExtra("start_month", start_month);
                    intent.putExtra("start_day", start_day);
                    intent.putExtra("end_year", end_year);
                    intent.putExtra("end_month", end_month);
                    intent.putExtra("end_day", end_day);
                    startActivityForResult(intent, 2);
                }
                break;

        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 1 && resultCode == RESULT_OK) {
            start_year = data.getIntExtra("start_year", calendar.get(Calendar.YEAR));
            start_month = data.getIntExtra("start_month", calendar.get(Calendar.MONTH) + 1);
            start_day = data.getIntExtra("start_day", calendar.get(Calendar.DAY_OF_MONTH));
            end_year = data.getIntExtra("end_year", calendar.get(Calendar.YEAR));
            end_month = data.getIntExtra("end_month", calendar.get(Calendar.MONTH) + 1);
            end_day = data.getIntExtra("end_day", calendar.get(Calendar.DAY_OF_MONTH) + 1);
            selectTime.setText(start_year + "."+start_month + "." + start_day + "-" +end_year+"."+ end_month + "." + end_day  );
            if (posistion == 0 && booknamelsit.size() > 1) {
                toAllBookManey();
            } else if (posistion > 0) {
                toOneBookManey(booknamelsit.get(posistion).getBookid());
            }

        }
        isPreferences.updateSp("start_year", start_year);
        isPreferences.updateSp("start_month", start_month);
        isPreferences.updateSp("start_day", start_day);
        isPreferences.updateSp("end_year", end_year);
        isPreferences.updateSp("end_month", end_month);
        isPreferences.updateSp("end_day", end_day);
    }

    private String isDan(int dan) {
        if (dan < 10) {
            return "0" + String.valueOf(dan);
        } else {
            return String.valueOf(dan);
        }
    }
    private String isAddAllDouhao(int num) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            df = new DecimalFormat("#,##0.00");
            return df.format((double)num/100);
        }
        BigDecimal bigDecimal=new BigDecimal((double)num/100);
        return String.valueOf(bigDecimal.setScale(2,BigDecimal.ROUND_HALF_UP).doubleValue());
    }
    private String
    isAddDouhao(int num) {
        return String.valueOf(num);

    }


}
